package com.tc.controller;

import com.tc.utils.UuidTools;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cai.tian on 2018/1/25.
 */
@RestController
@RequestMapping("/file")
public class FileRestAjax {
    private String img="jpeg,gif,png,jpg,JPEG,GIF,PNG,JPG";
    private String flash="swf,flv";

    @RequestMapping(value = "/fileUpload",method = RequestMethod.POST)
    public  ResponseEntity fileUpload(
            @RequestParam(value = "fileType",required = false) String fileType,
            @RequestParam(value = "responseType",required = false)String responseType ,
            @RequestParam(value = "CKEditorFuncNum",required = false)String cKEditorFuncNum,
            @RequestParam("upload")MultipartFile file) throws Exception{

        System.out.println(fileType);
        if(StringUtils.isEmpty(cKEditorFuncNum)){
            cKEditorFuncNum ="0";
        }
        System.out.println("-----上传-----");
        Long fileSize=0l;
        String fileName=null;
        String filePath=null;
        String suffix=null;
        String uuid= UuidTools.getUuid();
        if (!file.isEmpty()) {
            fileSize=file.getSize();
            fileName=file.getOriginalFilename();
            if(fileName.indexOf(".")<0){
               // return  "文件类型错误";
            }
            suffix=fileName.substring(fileName.indexOf(".")+1,fileName.length());
            if("imageUpload".equals(fileType)){
                int i = img.indexOf(suffix);
                if(i<0){
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.TEXT_HTML);
                    String r=null;
                    r="<font color=\"red\" size=\"2\">*图片格式不对</font>"; // 相对路径用于显示图片
                    return new ResponseEntity(r,headers, HttpStatus.OK);
                }
            }
            if("flashUpload".equals(fileType)){
                int i = flash.indexOf(suffix);
                if(i<0){
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.TEXT_HTML);
                    String r=null;
                    r="<font color=\"red\" size=\"2\">*flash 文件格式不对</font>"; // 相对路径用于显示图片
                    return new ResponseEntity(r,headers, HttpStatus.OK);
                }
            }

            fileName = uuid+"."+suffix;
            filePath="D:/temp/"+fileName;
            // 文件保存路径
            // 转存文件
            try {
                file.transferTo(new File(filePath));
            } catch (IOException e) {
               // return "文件保存失败";
            }
        }
        //https://admin.bfintra.com/proxy/demo-web/file/fileUpload?isAttachment=0&responseType=json 拽
        //https://admin.bfintra.com/proxy/demo-web/file/fileUpload?isAttachment=1&CKEditor=ckeditor1&CKEditorFuncNum=0&langCode=zh-cn 对话框
        //https://admin.bfintra.com/proxy/demo-web/file/fileUpload?isAttachment=1&CKEditor=ckeditor1&CKEditorFuncNum=0&langCode=zh-cn 文件上传
        if(!StringUtils.isEmpty(responseType) && "json".equals(responseType)){
            //return ;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            Map map = new HashMap();
            map.put("uploaded",1);
            map.put("fileName",uuid+suffix);
            map.put("url","/upload/images/"+fileName);
            return new ResponseEntity(map,headers, HttpStatus.OK);
        }
        String r="";
        // 返回“图像”选项卡并显示图片，这里是ckeditor返回图像并显示的代码
        r ="<script type=\"text/javascript\">";
        r+="window.parent.CKEDITOR.tools.callFunction(" + cKEditorFuncNum+ ",'/upload/images/"+fileName+"','')"; // 相对路径用于显示图片
        r+="</script>";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_HTML);
        return new ResponseEntity(r,headers, HttpStatus.OK);

    }


    @RequestMapping(value = "/presentFile")
    public ResponseEntity<byte[]> presentFile(@RequestParam(value = "isAttachment",required = false) String isAttachment,@RequestParam(value = "fileUuid") String fileUuid) throws Exception {
        System.out.println(fileUuid);
        System.out.println("--读取文件-");
        String path="D:/temp/"+fileUuid;
        File file=null;
        byte[] bytes =null;
        try {
            file=new File(path);
            bytes = FileUtils.readFileToByteArray(file);
        }catch (Exception o){

        }
        String name = file.getName();
        String fileType = getFileType(name);
        int i = img.indexOf(fileType);
        System.out.println(fileType);
        if(i>-1){
            System.out.println("-----图片文件-----");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.CREATED);
        }
        i = flash.indexOf(fileType);
        if(i>-1){
            System.out.println("-----flash文件-----");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_GIF);
            return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.CREATED);
        }
        System.out.println("-----普通文件-----");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", new String(name.getBytes("UTF-8"), "ISO8859-1"));  //解决文件名中文乱码问题
        return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.CREATED);

    }

    public String getFileType(String fileName){
        if(fileName.indexOf(".")<0){
            // return  "文件类型错误";
            return null;
        }
        return fileName.substring(fileName.indexOf(".")+1,fileName.length());
    }

}
